<?php
/**
 * @desc 支付宝.手机网页支付
 * @document https://docs.open.alipay.com/api_1/alipay.trade.wap.pay/
 * @author Vincent
 */

namespace young\payment;

class AliWapPay extends AliConfig
{
    /**
     * @param $data
     * @return string
     */
    public function run($data)
    {
        $this->setConfig($data['config']);
        return $this->handle($data['title'], $data['body'], $data['order_sn'], $data['amount'], $data['notify_url'], $data['return_url']);
    }

    /**
     * @param $title 商品标题
     * @param $body 商品描述
     * @param $orderSn 商户订单号
     * @param $amount 支付金额
     * @param $notifyUrl 异步通知地址
     * @param $returnUrl 同步通知地址
     * @return string
     */
    private function handle($title, $body, $orderSn, $amount, $notifyUrl, $returnUrl)
    {
        $common = [];
        $common['app_id'] = $this->appId;
        $common['method'] = 'alipay.trade.wap.pay';
        $common['format'] = self::FORMAT;
        $common['charset'] = self::CHARSET;
        $common['sign_type'] = self::SIGN_TYPE;
        $common['timestamp'] = date('Y-m-d H:i:s', time());
        $common['version'] = self::VERSION;
        $common['notify_url'] = $notifyUrl;
        $common['return_url'] = $returnUrl;
        $common['biz_content'] = [];
        $common['biz_content']['body'] = $body;
        $common['biz_content']['subject'] = $title;
        $common['biz_content']['out_trade_no'] = $orderSn;
        $common['biz_content']['total_amount'] = $amount;
        $common['biz_content']['product_code'] = 'QUICK_WAP_WAY';
        $common['biz_content']['goods_type'] = '1';
        $common['biz_content'] = json_encode($common['biz_content'], JSON_UNESCAPED_UNICODE);
        $common = array_filter($common);

        ksort($common);

        $rsa2 = new AliRsa2;
        $key = $rsa2->getRsaKeyValue($this->rsaPrivateKey, 'private');
        $rsa2->setKey($key);
        $common['sign'] = $rsa2->encrypt(urldecode(http_build_query($common)));
        return self::GETEWAY_URL . '?' . $rsa2->splicingString($common);
    }
}